package org.artofsolving.jodconverter.sample.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletConfig;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

public class TXConverterServlet extends HttpServlet {

  private static final long serialVersionUID = -591469426224201748L;
  private final Logger logger = Logger.getLogger(getClass().getName());
  private boolean isZip = true;
  ServletFileUpload fileUpload;
  Set<String> Supported = new HashSet<String>() {

    {
      this.add("pdf");
      this.add("doc");
      this.add("docx");
      this.add("html");
      this.add("rtf");
    }
  };

  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    //These two lines cause the sevelet not load problems.
   // WebappContext webappContext = WebappContext.get(config.getServletContext());
   // fileUpload = webappContext.getFileUpload();

    if (config.getInitParameter("zip") != null) {
      isZip = Boolean.getBoolean(config.getInitParameter("zip"));
    }
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String url = request.getParameter("url");
    
    if (request.getParameter("redirect")!=null)
    { 
     //HttpClient wc = new DefaultHttpClient();
       System.out.println("hrl="+url);
       url = url.replaceAll(" ", "%20");
        response.setContentType("application/ocstream");

          response.setHeader("Content-Disposition", "attachment; filename=temp.doc");
          InputStream is = new URL(url).openStream();
     IOUtils.copy(is, response.getOutputStream());
     is.close();
     response.getOutputStream().close();
     return;
    }
    //response.setBufferSize(1024 * 100);
    System.out.println(new java.util.Date());
    long t1 = new java.util.Date().getTime();

    boolean useOpenOffice = true;
   
    String f[] = url.split("\\$");
    String outputExtension = null;
    if (f.length == 1) {
      url = f[0];
    } else if (f.length == 2) {
      url = f[0];
      outputExtension = f[1];
    }

    String outputFileName = request.getParameter("outFile");
    String cache = request.getParameter("cache");
    //String outputExtension = request.getParameter("target");
    if (url != null) {
      url = java.net.URLDecoder.decode(url);
    }
    if (outputFileName != null) {
      outputFileName = java.net.URLDecoder.decode(outputFileName);
    } else {
      outputFileName = url.hashCode() + ".doc";
    }

    if (outputExtension == null) {
      outputExtension = FilenameUtils.getExtension(outputFileName);
    }
   System.out.println("***888" + (new java.util.Date().getTime() - t1));
    String baseName = url.substring((url.lastIndexOf('/') + 1));
    if (baseName.indexOf("?") > 0) {
      baseName = baseName.substring(0, baseName.indexOf("?"));
    }
    String inputExtension = FilenameUtils.getExtension(baseName);
    baseName = FilenameUtils.getBaseName(baseName);
    String hash = MungPass(url);
    File outputFile = new File(hash + "." + outputExtension);
    File inputFile = new File(MungPass(url) + "." + inputExtension);
    if ("false".equals(cache)) {
      outputFile.delete();
      inputFile.delete();
    }

      if (!inputFile.exists()) {
        OutputStream os = new FileOutputStream(inputFile);
        //FileOutputStream os = new FileOutputStream(inputFile);
        try {
          //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.entp.attws.com", 8080));
          //IOUtils.copy(new URL(url).openConnection(proxy).getInputStream(), os);
          IOUtils.copy(new URL(url).openStream(), os);
        } catch (Exception e) {
          e.printStackTrace();
          response.getWriter().println("converting error");
          return;
        } finally {
          os.close();
        }
    }
      System.out.println("*****" + inputExtension);
      if (Supported.contains(inputExtension)) {
        try {
         
          response.setContentType("text/plain");
          response.setHeader("Content-Disposition", "attachment; filename=" + baseName + "." + outputExtension);
          sendFile(inputFile, response);
           System.out.println("==" + (new java.util.Date().getTime() - t1));
        } catch (Exception exception) {
          //logger.severe(String.format("failed conversion: %s [%db] to %s; %s; input file: %s", inputExtension, inputFile.length(), outputExtension, exception, inputFile.getName()));
          throw new ServletException("conversion failed", exception);
        } finally {
          if (inputFile != null && ("false").equals(cache)) {
            inputFile.delete();
          }
          if (cache != null && ("false").equals(cache)) {
            outputFile.delete();
          }
        }
      }
  }

  private void sendFile(File file, HttpServletResponse response) throws IOException {
    InputStream inputStream = null;

    try {
      System.out.println(new java.util.Date());
      long t1 = new java.util.Date().getTime();
      inputStream = new FileInputStream(file);
      OutputStream os =  response.getOutputStream();
        String inputExtension = FilenameUtils.getExtension(file.getName());
      if (isZip && Supported.contains(inputExtension)) {
        os = new org.apache.commons.codec.binary.Base64OutputStream(os);
        ZipOutputStream zos = new java.util.zip.ZipOutputStream(os);
        ZipEntry entry = new ZipEntry(file.getName());
        zos.putNextEntry(entry);
        os = zos;
      }
      IOUtils.copy(inputStream, os);
      os.close();
      //

    } catch (Exception e) {
      e.printStackTrace();


    } finally {
      IOUtils.closeQuietly(inputStream);
    }
  }

  private void writeUploadedFile(FileItem uploadedFile, File destinationFile) throws ServletException {
    try {
      uploadedFile.write(destinationFile);
    } catch (Exception exception) {
      throw new ServletException("error writing uploaded file", exception);




    }
    uploadedFile.delete();




  }

  private FileItem getUploadedFile(ServletFileUpload fileUpload, HttpServletRequest request) throws FileUploadException {
    @SuppressWarnings("unchecked")
    List<FileItem> fileItems = fileUpload.parseRequest(request);
    for (FileItem fileItem : fileItems) {
      if (!fileItem.isFormField()) {
        return fileItem;




      }
    }
    return null;




  }

 

  public static String MungPass(String pass) {
    try {
      MessageDigest m = MessageDigest.getInstance("MD5");




      byte[] data = pass.getBytes();
      m.update(data, 0, data.length);
      BigInteger i = new BigInteger(1, m.digest());

      return String.format("%1$032X", i);




    } catch (Exception e) {
      return pass.hashCode() + "";



    }
  }


  public static void main(String s[]) throws Exception {
    Date d = new Date();
    String surl = "http://localhost:9080/elconverter/txconv/?url=http://localhost:9080/elconverter/docs/Oscar.rtf";
    URL url = new URL(surl);
    IOUtils.copy(url.openStream(), new FileWriter("c:\\temp\\a.txt"));
    System.out.println(new Date().getTime() - d.getTime());

  }
}

